#include "timer.h"
#include <time.h>
#include <cassert>

#ifdef WIN32
void DecoTimer::startTimer(void)
{
	resetTimer();
}

void DecoTimer::resetTimer(void)
{
	m_startTime = clock();
	m_isStarted = true;
	assert(m_startTime != -1);
}
void DecoTimer::pauseTimer(void)
{
	if (!m_isPaused)
	{
		m_pauseTime = clock();
		assert(m_pauseTime != -1);
		m_isPaused = true;

	}
}
void DecoTimer::resumeTimer(void)
{
	if (m_isPaused)
	{
		clock_t resumeTime;
		resumeTime = clock();
		assert(resumeTime != -1);
		m_startTime += resumeTime - m_pauseTime;
		m_isPaused = false;
		
	}
}
double DecoTimer::getCurrentTime(void)
{
	if (m_isPaused)
	{
		return ((double)(m_pauseTime - m_startTime) / CLK_TCK);
	} else {
		m_nowTime = clock();
		return ((double)(m_nowTime - m_startTime) / CLK_TCK);
	}

}
#else
#include <sys/time.h>

void DecoTimer::startTimer(void)
{
	resetTimer();
}

void DecoTimer::resetTimer(void)
{
  gettimeofday(&m_startTime, NULL);
  m_isStarted = true;
}
void DecoTimer::pauseTimer(void)
{
	if (!m_isPaused)
	{
	  gettimeofday(&m_pauseTime, NULL);

		m_isPaused = true;

	}
}
void DecoTimer::resumeTimer(void)
{
	if (m_isPaused)
	{
		timeval resumeTime;
		gettimeofday(&resumeTime, NULL);
		m_startTime.tv_sec += resumeTime.tv_sec - m_pauseTime.tv_sec;
		m_isPaused = false;
		
	}
}
double DecoTimer::getCurrentTime(void)
{
	if (m_isPaused)
	{
	  return timeDiffInSecond(m_pauseTime, m_startTime);
	} else {
	  gettimeofday(&m_nowTime, NULL);
	  return timeDiffInSecond(m_nowTime, m_startTime);
	}

}

double DecoTimer::timeDiffInSecond(timeval time1, timeval time2)
{
  double elapsedTime = (time1.tv_sec - time2.tv_sec);
  elapsedTime += (time1.tv_usec - time2.tv_usec) / 1000000.0;
  return elapsedTime;
}
#endif
